<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-28
 * Time: 19:35
 */

namespace app\api\service\money;


use app\api\model\User;
use app\api\model\UserMoney;
use app\api\service\Token;
use app\lib\exception\ParameterException;

class MinMoneySer extends Token
{
    /**
     * 1.判断金额数量
     * 2.判断用户余额
     * 3.减金额 添加记录
     */

    // 用户信息
    private $user;

    // 余额
    private $money;

    function __construct($money)
    {
        $this->user = User::get(self::getCurrentUid());
        $this->money = round($money,2);
    }

    // 入口方法
    public function entrance()
    {
        return $this->judgeMoney();
    }

    // 判断金额以及用户金额
    private function judgeMoney()
    {
        if(!$this->money) {
            throw new ParameterException([
                'msg' => [
                    'money' => '请输入正确的支付金额'
                ]
            ]);
        }
        if($this->money <= 0) {
            throw new ParameterException([
                'msg' => [
                    'money' => '请输入正确的支付金额'
                ]
            ]);
        }
        if(!is_numeric($this->money)) {
            throw new ParameterException([
                'msg' => [
                    'money' => '请输入正确的支付金额'
                ]
            ]);
        }
        if($this->money > $this->user['money']) {
            throw new ParameterException([
                'msg' => [
                    'money' => '余额不足'
                ]
            ]);
        }
        return $this->updateMoney();
    }

    // 减少金额
    private function updateMoney()
    {
        UserMoney::create([
            'money' => $this->money,
            'user_id' => $this->user['id'],
            'type' => 3,
            'user_money' => $this->user['money'],
            'order_id' => 0
        ]);
        User::where('id',$this->user['id'])->update([
            'money' => round($this->user['money'] - $this->money,2)
        ]);
        return writeJson(202, [], '支付成功！');
    }
}